# user_app/utils.py 优化示例
import jwt
import time
import uuid
from django.conf import settings

# 生成访问令牌
def generate_access_token(user_id):
    payload = {
        'id': user_id,
        'iat': time.time(),
        'exp': time.time() + settings.JWT_ACCESS_TOKEN_EXPIRATION,
        'jti': str(uuid.uuid4()),  # 添加JWT ID防止重放攻击
        'type': 'access'
    }
    return jwt.encode(payload, settings.JWT_SECRET_KEY, algorithm='HS256')

# 生成刷新令牌
def generate_refresh_token(user_id):
    payload = {
        'id': user_id,
        'iat': time.time(),
        'exp': time.time() + settings.JWT_REFRESH_TOKEN_EXPIRATION,
        'jti': str(uuid.uuid4()),
        'type': 'refresh'
    }
    return jwt.encode(payload, settings.JWT_REFRESH_SECRET_KEY, algorithm='HS256')

# 验证token
def verify_token(token, token_type='access'):
    try:
        secret_key = settings.JWT_SECRET_KEY if token_type == 'access' else settings.JWT_REFRESH_SECRET_KEY
        payload = jwt.decode(token, secret_key, algorithms=['HS256'])
        
        # 验证token类型
        if payload.get('type') != token_type:
            return None
        
        return payload
    except jwt.ExpiredSignatureError:
        # token过期
        return {'expired': True, 'id': jwt.decode(token, secret_key, algorithms=['HS256'], options={'verify_exp': False}).get('id')}
    except Exception:
        return None